package com.yuyuto.conn;

import android.content.Context;

import com.yuyuto.conn.cookie.PersistentCookieStore;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Demon on 2016/11/8.
 */

public class RetrofitManager {

    private OkHttpClient client;
    private static RetrofitManager manager;
    public IYuyutoConnService service;
    private Context mContext;

    private RetrofitManager(Context context) {
        mContext = context;
        initialization();
    }

    public static RetrofitManager getInstance(Context context) {
        if (manager == null) {
            manager = new RetrofitManager(context);
        }
        return manager;
    }

    public OkHttpClient getOkHttpClient() {
        return client;
    }

    private void initialization() {

        int[] certificates = new int[]{R.raw.nginx};
        String[] hosts = new String[]{"http://t1.rhxxkj.com:8080", "https://192.168.1.52/"};
        TrustManagerFactory trustManagerFactory = SSLUtil.asd(mContext, certificates);
        SSLSocketFactory sslSocketFactory = SSLUtil.getSSLSocketFactory(trustManagerFactory);
        client = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
//                .socketFactory(sslSocketFactory)
//                .hostnameVerifier(SSLUtil.getHostnameVerifier(hosts))

//                .certificatePinner(new CertificatePinner.Builder()
//                        .add("https://app.yuyuto.com/", "sha256/LBDSM+i3ngFrmKgxZ+fJWPhQyjuBEvpGlO19gxcyv7o=")
//                        .build())
                .cookieJar(new CookiesManager())
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request newRequest = chain.request().newBuilder()
                                .addHeader("platform", "android")
                                .addHeader("appVersion", BuildConfig.VERSION_NAME)
                                .addHeader("USER-AGENT", BuildConfig.VERSION_NAME)
                                .addHeader("Content-Type", "text/html; charset=UTF-8")
                                .build();
                        return chain.proceed(newRequest);
                    }
                })
                .build();

        // print Log
//        client.interceptors().add(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
//
//            @Override
//            public void log(String message) {
//                Logger.d("Http_response=============>" + message);
//            }
//        }));

        Retrofit retrofit = new Retrofit.Builder()
//                .baseUrl("https://managesit.mumakid.com/")
                .baseUrl("http://t1.rhxxkj.com:8080/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();

        service = retrofit.create(IYuyutoConnService.class);
    }

    /**
     * 自动管理Cookies
     */
    private class CookiesManager implements CookieJar {
        private final PersistentCookieStore cookieStore = new PersistentCookieStore(mContext.getApplicationContext());

        @Override
        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
            if (cookies != null && cookies.size() > 0) {
                for (Cookie item : cookies) {
                    cookieStore.add(url, item);
                }
            }
        }

        @Override
        public List<Cookie> loadForRequest(HttpUrl url) {
            List<Cookie> cookies = cookieStore.get(url);
            return cookies;
        }
    }
}
